package com.eduplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import com.eduplatform.dto.StudentDTO;
import com.eduplatform.entity.School;
import com.eduplatform.entity.User;
import com.eduplatform.mapper.SchoolMapper;
import com.eduplatform.mapper.UserMapper;
import com.eduplatform.service.StudentService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学生服务实现类
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    // 默认密码
    private static final String DEFAULT_PASSWORD = "123456";

    @Override
    public IPage<StudentDTO> pageStudents(int page, int size, Long schoolId, Integer educationLevel, String keyword) {
        // 构建查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        // 只查询学生角色
        wrapper.eq(User::getRole, 0);
        // 按学校ID筛选
        if (schoolId != null) {
            wrapper.eq(User::getSchoolId, schoolId);
        }
        // 按教育阶段筛选
        if (educationLevel != null) {
            wrapper.eq(User::getEducationLevel, educationLevel);
        }
        // 关键词搜索（姓名、用户名）
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w
                    .like(User::getNickname, keyword)
                    .or()
                    .like(User::getUsername, keyword));
        }
        // 按创建时间降序排序
        wrapper.orderByDesc(User::getCreateTime);

        // 执行分页查询
        Page<User> userPage = new Page<>(page, size);
        IPage<User> userIPage = userMapper.selectPage(userPage, wrapper);

        // 转换为DTO
        IPage<StudentDTO> resultPage = userIPage.convert(this::convertToDTO);

        // 获取学校信息
        List<Long> schoolIds = resultPage.getRecords().stream()
                .map(StudentDTO::getSchoolId)
                .distinct()
                .collect(Collectors.toList());

        if (!schoolIds.isEmpty()) {
            List<School> schools = schoolMapper.selectBatchIds(schoolIds);

            // 设置学校名称
            for (StudentDTO studentDTO : resultPage.getRecords()) {
                for (School school : schools) {
                    if (school.getId().equals(studentDTO.getSchoolId())) {
                        studentDTO.setSchoolName(school.getName());
                        break;
                    }
                }
            }
        }

        return resultPage;
    }

    @Override
    public StudentDTO getStudentDetail(Long id) {
        User user = userMapper.selectById(id);
        if (user == null || !user.getRole().equals(0)) {
            return null;
        }

        StudentDTO studentDTO = convertToDTO(user);

        // 获取学校信息
        if (studentDTO.getSchoolId() != null) {
            School school = schoolMapper.selectById(studentDTO.getSchoolId());
            if (school != null) {
                studentDTO.setSchoolName(school.getName());
            }
        }

        return studentDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addStudent(StudentDTO studentDTO) {
        // 检查用户名是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, studentDTO.getUsername());
        User existUser = userMapper.selectOne(wrapper);
        if (existUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建用户对象
        User user = new User();
        BeanUtils.copyProperties(studentDTO, user);

        // 设置角色为学生
        user.setRole(0);

        // 设置默认密码
        String password = StringUtils.hasText(studentDTO.getPassword()) ? studentDTO.getPassword() : DEFAULT_PASSWORD;
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

        // 设置创建和更新时间
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        return userMapper.insert(user) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStudent(StudentDTO studentDTO) {
        // 检查学生是否存在
        User existUser = userMapper.selectById(studentDTO.getId());
        if (existUser == null || !existUser.getRole().equals(0)) {
            throw new RuntimeException("学生不存在");
        }

        // 如果修改用户名，需要检查是否已存在
        if (!existUser.getUsername().equals(studentDTO.getUsername())) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUsername, studentDTO.getUsername());
            User userWithSameUsername = userMapper.selectOne(wrapper);
            if (userWithSameUsername != null) {
                throw new RuntimeException("用户名已存在");
            }
        }

        // 更新用户对象
        User user = new User();
        BeanUtils.copyProperties(studentDTO, user);

        // 保持原有角色和密码
        user.setRole(existUser.getRole());
        user.setPassword(existUser.getPassword());

        // 设置更新时间
        user.setUpdateTime(new Date());

        return userMapper.updateById(user) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteStudent(Long id) {
        // 检查学生是否存在
        User existUser = userMapper.selectById(id);
        if (existUser == null || !existUser.getRole().equals(0)) {
            throw new RuntimeException("学生不存在");
        }

        return userMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchImportStudents(List<StudentDTO> students) {
        if (students == null || students.isEmpty()) {
            return false;
        }

        List<User> userList = new ArrayList<>();
        Date now = new Date();

        for (StudentDTO studentDTO : students) {
            // 检查用户名是否存在
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUsername, studentDTO.getUsername());
            User existUser = userMapper.selectOne(wrapper);
            if (existUser != null) {
                throw new RuntimeException("用户名 " + studentDTO.getUsername() + " 已存在");
            }

            // 创建用户对象
            User user = new User();
            BeanUtils.copyProperties(studentDTO, user);

            // 设置角色为学生
            user.setRole(0);

            // 设置默认密码
            String password = StringUtils.hasText(studentDTO.getPassword()) ? studentDTO.getPassword()
                    : DEFAULT_PASSWORD;
            user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

            // 设置创建和更新时间
            user.setCreateTime(now);
            user.setUpdateTime(now);

            userList.add(user);
        }

        // 批量插入
        for (User user : userList) {
            userMapper.insert(user);
        }

        return true;
    }

    @Override
    public List<StudentDTO> getStudentsBySchoolId(Long schoolId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRole, 0);
        wrapper.eq(schoolId != null, User::getSchoolId, schoolId);
        wrapper.orderByAsc(User::getNickname);

        List<User> userList = userMapper.selectList(wrapper);
        return userList.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStudentStatus(Long id, Integer status) {
        // 检查学生是否存在
        User existUser = userMapper.selectById(id);
        if (existUser == null || !existUser.getRole().equals(0)) {
            throw new RuntimeException("学生不存在");
        }

        // 在User实体中没有status字段，但我们可以通过isDeleted字段来模拟状态
        // 0-启用（isDeleted=0），1-禁用（isDeleted=1）
        User user = new User();
        user.setId(id);
        user.setIsDeleted(status == 0 ? 1 : 0); // 反转逻辑以匹配状态定义
        user.setUpdateTime(new Date());

        return userMapper.updateById(user) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resetStudentPassword(Long id) {
        // 检查学生是否存在
        User existUser = userMapper.selectById(id);
        if (existUser == null || !existUser.getRole().equals(0)) {
            throw new RuntimeException("学生不存在");
        }

        User user = new User();
        user.setId(id);
        user.setPassword(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
        user.setUpdateTime(new Date());

        return userMapper.updateById(user) > 0;
    }

    /**
     * 将用户实体转换为学生DTO
     */
    private StudentDTO convertToDTO(User user) {
        if (user == null) {
            return null;
        }

        StudentDTO studentDTO = new StudentDTO();
        BeanUtils.copyProperties(user, studentDTO);
        return studentDTO;
    }
}